#include "common.h"

void init_flash(void)
{
    while (FLASH->SR & (1 << 0))
        ;
    FLASH->ACR = (2 << 0) | (1 << 4);
    while (!(FLASH->ACR & (1 << 5)))
        ;
}

void flash_unlock(void)
{
    while (FLASH->SR & (1 << 0))
        ;
    FLASH->KEYR = FLASH_KEY1;
    FLASH->KEYR = FLASH_KEY2;
    while (FLASH->SR & (1 << 0))
        ;
}

void flash_lock(void)
{
    while (FLASH->SR & (1 << 0))
        ;
    FLASH->CR |= (1 << 31);
    while (FLASH->SR & (1 << 0))
        ;
}

void flash_clear_flag(void)
{
    while (FLASH->SR & (1 << 0))
        ;
    FLASH->SR = (1 << 2) | (1 << 4) | (1 << 5);
    while (FLASH->SR & (1 << 0))
        ;
}

void flash_erase_page(unsigned int page)
{
    while (FLASH->SR & (1 << 0))
        ;
    FLASH->CR |= (1 << 1);
    FLASH->AR = page;
    FLASH->CR |= (1 << 6);
    delay_time(1);
    while (FLASH->SR & (1 << 0))
        ;
    FLASH->CR &= ~(1 << 1);
}

void flash_write_halfword(unsigned short *addr, unsigned short *data, unsigned int halfword_num)
{
    flash_unlock();
    flash_clear_flag();
    flash_erase_page((unsigned int)addr);

    while (FLASH->SR & (1 << 0))
        ;
    FLASH->CR |= (1 << 0);
    for (unsigned int i = 0; i < halfword_num; i++) {
        addr[i] = data[i];
        while (FLASH->SR & (1 << 0))
            ;
    }
    FLASH->CR &= ~(1 << 0);
    flash_clear_flag();
    flash_lock();
}

void flash_read_halfword(unsigned short *addr, unsigned short *data, unsigned int halfword_num)
{
    for (unsigned int i = 0; i < halfword_num; i++) {
        data[i] = addr[i];
    }
}
